package com.belizer.demo.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Demo2 {
    static ThreadPoolExecutor executorService = new ThreadPoolExecutor(5, 5, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

    public static void main(String[] args) throws InterruptedException {
        //用来监控线程池的执行状态，注意初始化用ThreadPoolExecutor，非executorService
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    System.out.println(executorService);
                    TimeUnit.SECONDS.sleep(3);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();

        //记录执行时间
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            int x = i;
            CompletableFuture.runAsync(() -> {
                try {
                    System.out.println("running..." + x);
                    if (x == 7) {
                        TimeUnit.SECONDS.sleep(20);
                    }else {
                        TimeUnit.SECONDS.sleep(5);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, executorService).toCompletableFuture().whenComplete((aVoid, throwable) -> {
                //每个任务执行完成的需要的时间
                System.out.println(System.currentTimeMillis() - start);
            });
        }

        //执行shutdown
        executorService.shutdown();
        System.out.println("start shutdown ...");
        //等待执行结束
        executorService.awaitTermination(2, TimeUnit.MINUTES);

    }



}
